import Vue from "vue";
import VueRouter from "vue-router";
import axios from "axios";

const qs = require("qs");

const httpAdminPost = (url: string, params: any = null) =>
  axios.post(`/pauth/api/v1${url}`, params);

const httpAdminGetWithToken = (url: string, params: any = null) =>
  axios.get(`/pauth/api/v1${url}`, {
    params,
    headers: { "X-Auth-Token": localStorage.getItem("accessToken") },
  });

const httpAdminPostWithToken = (url: string, params: any = null) =>
  axios.post(`/pauth/api/v1${url}`, params, {
    headers: { "X-Auth-Token": localStorage.getItem("accessToken") },
  });

const httpGetWithToken = (url: string, params: any = null) =>
  axios.get(`/bcpower/api/v1${url}`, {
    params,
    headers: { "X-Auth-Token": localStorage.getItem("accessToken") },
  });

const httpPostWithToken = (url: string, params: any = null) =>
  axios.post(`/bcpower/api/v1${url}`, params, {
    headers: { "X-Auth-Token": localStorage.getItem("accessToken") },
  });

function handleNoAuth(router: VueRouter) {
  if (router.currentRoute.fullPath.indexOf("login") > -1) {
    return;
  }
  router.replace({
    path: "/login",
    query: {
      redirect: router.currentRoute.fullPath,
    },
  });
}
export default class Api {
  constructor(router: VueRouter) {
    axios.interceptors.request.use(
      (config: any) => {
        if (config.method === "get") {
          config.paramsSerializer = (params: any) => {
            return qs.stringify(params, { arrayFormat: "repeat" });
          };
        }
        return config;
      },
      (err: any) => {
        return Promise.reject(err);
      }
    );
    axios.interceptors.response.use(
      (res: any) => {
        return res.data;
      },
      (err: any) => {
        console.error(err.response);
        if (err.response != null) {
          const { message, code } = err.response.data;
          if (err.response.status === 400) {
            if (code && code === 1001 && message && message.indexOf('Missing X-Auth-Token') > -1) {
              handleNoAuth(router);
            }
          }
          if (err.response.status === 401) {
            handleNoAuth(router);
          }
          if (err.response.status === 500) {
            Vue.prototype.$notify.error({
              title: "服务器错误",
              message: `${err.response.data.exception}(${err.response.data.path})`,
              duration: 0,
            });
          }
          Vue.prototype.$errorMessage = message;
          Vue.prototype.$message.error(message);
        }
        return Promise.reject(err);
      }
    );
  }

  public Login = (params: any) => httpAdminPost("/session/login", params);
  public getTradePeriodsGet = (params: any) =>
    httpGetWithToken("/trade_periods/get", params)
  public getTradePeriodsQuery = (params: any) =>
    httpGetWithToken("/trade_periods/query", params)
  public getBlocksQuery = (params: any) =>
    httpGetWithToken("/bc/blocks/query", params)
  public getBlocksGet = (params: any) =>
    httpGetWithToken("/bc/blocks/get", params)
  public getOrdersStat = (params: any) =>
    httpGetWithToken("/orders/stat", params)
  public getOffersQuery = (params: any) =>
    httpGetWithToken("/offers/query", params)
  public getOrdersQuery = (params: any) =>
    httpGetWithToken("/orders/query", params)
  public getOrdersGet = (params: any) =>
    httpGetWithToken("/orders/get", params)
  public creatOffers = (params: any) =>
    httpPostWithToken("/offers/create", params)
  public creatOrder = (params: any) =>
    httpPostWithToken("/orders/create", params)
  public cancelOrder = (params: any) =>
    httpPostWithToken("/orders/cancel", params)
  public getOffersGet = (params: any) =>
    httpGetWithToken("/offers/get", params)
  public getBranchesQuery = (params: any) =>
    httpGetWithToken("/admin/net_topo/branches/query", params)
  public getBusesQuery = (params: any) =>
    httpGetWithToken("/admin/net_topo/buses/query", params)

  // 账户管理相关
  public getAccountsQuery = (params: any) =>
    httpAdminGetWithToken("/admin/accounts/query", params)
  public accountReview = (params: any) =>
    httpAdminPostWithToken("/admin/accounts/review", params)
  public getAccountsSyscfg = () => httpGetWithToken("/admin/syscfg/get");
  public updateSysCfg = (params: any) =>
    httpPostWithToken("/admin/syscfg/update", params)
  public getAaccounts = () => httpAdminGetWithToken("/accounts/get");
  public accountResetPasswd = (params: any) =>
    httpAdminPostWithToken("/accounts/reset_passwd", params)
  public logout = (params: any) =>
    httpAdminPostWithToken("/session/logout", params)

  // 系统管理-运行统计
  public getAdminTxns = (params: any) =>
    httpGetWithToken("/admin/txns/stat", params)

  public regin = (params: any) => httpAdminPost("/accounts/register", params);
}
